package com.jk.hly.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jk.hly.demo.bean.ReceivePage;
import com.jk.hly.demo.bean.SendPage;
import com.jk.hly.demo.bean.User;
import com.jk.hly.demo.util.RestClientFactory;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("elast")
public class ESController {


     @ResponseBody
     @RequestMapping("addElast")
     public  String  addElast(User user){
         //1.获取ES的连接
         RestHighLevelClient highLevelClient = RestClientFactory.getHighLevelClient();
         //2.指定存放的位置"
         IndexRequest indexRequest = new IndexRequest("hly","user");
         System.out.println(indexRequest);

         //3.user对象-->JSON字符串
         String str = JSONObject.toJSONString(user);
         System.out.println(str);

         indexRequest.source(str, XContentType.JSON);
         System.out.println(indexRequest);
         //同步
        /* try {
             highLevelClient.index(indexRequest);
         } catch (IOException e) {
             e.printStackTrace();
         }*/

        //异步  有回调函数
         highLevelClient.indexAsync(indexRequest, new ActionListener<IndexResponse>() {
             @Override
             public void onResponse(IndexResponse indexResponse) {
                 System.out.println("成功的回调函数");

             }

             @Override
             public void onFailure(Exception e) {
                 System.out.println("失败的回调函数");
             }
         });
         return  "";
     }


     @ResponseBody
     @RequestMapping(value="deleteUser/{id}")//,method = RequestMethod.DELETE
     public  String  deleteUser(@PathVariable("id") String  id){
         RestHighLevelClient highLevelClient = RestClientFactory.getHighLevelClient();

         DeleteRequest deleteRequest = new DeleteRequest("hly","user",id);

         highLevelClient.deleteAsync(deleteRequest, new ActionListener<DeleteResponse>() {
             @Override
             public void onResponse(DeleteResponse deleteResponse) {

             }

             @Override
             public void onFailure(Exception e) {

             }
         });

         return  "";
     }



     @ResponseBody
     @RequestMapping("queryAll")
     public SendPage queryAll(ReceivePage  page,String  str) throws IOException {
         SearchRequest searchRequest = new SearchRequest("hly");  //先new一个放索引的
         SearchResponse search = RestClientFactory.getHighLevelClient().search(searchRequest);//

         SearchSourceBuilder searchsourcebuilder = new SearchSourceBuilder();  //query   new一个query
         BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();  //boll    new一个bool



         SendPage sp =new  SendPage();  //返回的数据
         ArrayList<User> list = new ArrayList<User>(); //往 SendPage 放入的list
         if(!StringUtils.isEmpty(str.trim())){

             MatchQueryBuilder username = QueryBuilders.matchQuery("username", str);  //查询条件的字段名称和值
             BoolQueryBuilder must = boolQueryBuilder.must(username);  // 先将查询条件放入 bool中

             searchsourcebuilder.query(must);     //再放入query中

             searchRequest.source(searchsourcebuilder);   //再放入索引容器中

             SearchResponse search1 = RestClientFactory.getHighLevelClient().search(searchRequest); //查询
             SearchHit[] hits = search1.getHits().getHits();
             for (SearchHit hit : hits) {
                 String st = hit.getSourceAsString();
                 String id = hit.getId();
                 User user = JSONObject.parseObject(st, User.class);
                 user.setId(id);
                 list.add(user);
             }
             sp.setTotal(list.size());
             sp.setRows(list);

             System.out.println("非空");
         }else {
             System.out.println("空");

             SearchHit[] hits = search.getHits().getHits();

             for (SearchHit hit : hits) {
                 String st = hit.getSourceAsString();
                 String id = hit.getId();
                 User user = JSONObject.parseObject(st, User.class);
                 user.setId(id);
                 list.add(user);
             }
                sp.setTotal(list.size());
                sp.setRows(list);
            }
         return sp;
     }

}
